package work2;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Lib {
	private String text;
    private int chars;
    private int lines;
    private int words;
    private Map<String,Integer> wordsMap;  //Integer可以表示null，而int不能
    private boolean isSetWordMap = false;  //用于控制共用函数只运行一次

    public Lib(String text)
    {
        this.text = text;
    }
    
    int countChar()
    {
        chars = text.length();
        return chars;
    }
    
    int countLine() {
    	Matcher m = Pattern.compile("(^|\n)\\s*\\S+").matcher(text);
    	lines = 0;
    	while (m.find())
    	{
    	    lines ++;
    	}
		return lines;
    }
    
    int countWord() {
    	if(!isSetWordMap)
    		setWordMap();
    	return words;
    }
    
    Map<String,Integer> getWordsTop10(){
    	if(!isSetWordMap)
    		setWordMap();
    	wordsMap =
    			wordsMap
                .entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer> comparingByValue() //按值降序
                        .reversed()
                        .thenComparing(Map.Entry.comparingByKey()))//按key字典序升序
                .limit(10)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
		return wordsMap;
    }
    
    void setWordMap() {
    	Matcher m = Pattern.compile("(^|[^A-Za-z0-9])([a-zA-Z]{4}[a-zA-Z0-9]*)").matcher(text);
    	wordsMap = new HashMap<String, Integer>();
        while(m.find())
        {
            String Word = m.group(2).toString().toLowerCase();
            Integer wordvalue = wordsMap.get(Word);
            if(wordvalue == null)
            {
                words++;
            	wordsMap.put(Word, 1);
            }
            else
            {
            	wordsMap.put(Word, wordvalue + 1);   //在原本计数上+1
            }
        }
        isSetWordMap = true;
    }
}
